<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
 /* 
 * @package   UserPerm SimpleLoginSecure extender
 * @version   1.0.0
 * @author    Anton Fedianin, Dark Angel <dark666.a[at]gmail.com>
 * @copyright Copyright (c) 2009, Anton Fedianin
 * @license   http://www.gnu.org/licenses/gpl-3.0.txt
 * @link      http://slash.su
 */
 
require('SimpleLoginSecure.php');

class UserPerm extends SimpleLoginSecure
{
	var $CI;
	var $user_perm_table = 'permissions';
	
	function checkPerm ($user_id, $need, $mid = '', $pid = '', $type = '') 
	{
		if($user_id == '' || $user_id == 0) return FALSE;
		
		$this->CI =& get_instance();
		$data = array (
						'user_id' => $user_id,
						'perm' => $need
					);
		if($mid != '') $data['mid'] = $mid;
		if($pid != '') $data['mid'] = $pid;
		if($type != '') $data['type'] = $type;

		$this->CI->db->where($data);
		$query = $this->CI->db->get($this->user_perm_table);
		
		if($query -> num_rows() > 0)
			return TRUE;
		$this->CI->db->where('user_id', $user_id, 'type', 'adm');
		$query = $this->CI->db->get($this->user_perm_table);
		if($query -> num_rows() > 0)
			return TRUE;
			
		 return FALSE;
	}
	
	function getPerm ($user_id, $mid = '', $pid = '', $type = '') 
	{
		$this->CI =& get_instance();
		$data = array (
						'user_id' => $user_id,
					);
		if($mid != '') $data['mid'] = $mid;
		if($pid != '') $data['mid'] = $pid;
		if($type != '') $data['type'] = $type;
		
		$this->CI->db->where($data);
		$query = $this->CI->db->get($this->user_perm_table);
		if($query -> num_rows() > 0){
			$t = $query -> result();
			return $t['perm'];
		}
	}
	
	function edit($user_id, $user_nick = '', $user_pass = '', $user_repass = '') 
	{
		$this->CI =& get_instance();
		
		$data = array(
			'user_modified' => date('c')
		);
		//Pass
		if($user_pass!='' && $user_repass === $user_pass){
			//Hash user_pass using phpass
			$hasher = new PasswordHash(PHPASS_HASH_STRENGTH, PHPASS_HASH_PORTABLE);
			$user_pass_hashed = $hasher->HashPassword($user_pass);
			$data['user_pass'] = $user_pass_hashed;
		}
		//
		
		//Nick
		if($user_nick!=''){ $data['nick'] = $user_nick; }
		//
		
		//Insert account into the database
		$this->CI->db->set($data); 
		$this->CI->db->where('user_id',$user_id);
		if(!$this->CI->db->update($this->user_table)) {
			return FALSE;
		} else {
			//Destroy old session
			$this->CI->session->sess_destroy();
			//Create a fresh, brand new session
			$this->CI->session->sess_create();
			$this->CI->db->where('user_id', $user_id); 
			$query = $this->CI->db->getwhere($this->user_table);
			if ($query->num_rows() > 0) 
			{	$user_data = $query->row_array(); 
				//Set session data
				unset($user_data['user_pass']);
				$user_data['user'] = $user_data['user_email']; // for compatibility with Simplelogin
				$user_data['logged_in'] = TRUE;
				$this->CI->session->set_userdata($user_data);
			}
		}
		return TRUE;
	}
		
}
?>
